package esb.chapter8.transaction.bean;

import javax.annotation.Resource;
import javax.jbi.component.ComponentContext;
import javax.jbi.messaging.DeliveryChannel;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.MessagingException;
import javax.jbi.messaging.NormalizedMessage;
import javax.transaction.TransactionManager;

import org.apache.log4j.Logger;
import org.apache.servicemix.MessageExchangeListener;
import org.apache.servicemix.components.util.ComponentSupport;
import org.apache.servicemix.jbi.jaxp.SourceTransformer;

public class TransactionComponent extends ComponentSupport implements MessageExchangeListener {
	
	private final static Logger logger = Logger.getLogger(TransactionComponent.class);
	private SourceTransformer sourceTransformer = new SourceTransformer();
	@Resource
	private DeliveryChannel channel;
	
	@Resource 
	private ComponentContext context;

    public void onMessageExchange(MessageExchange exchange) throws MessagingException {
    	if (exchange.getStatus() != ExchangeStatus.ACTIVE) return;
        try {
        	NormalizedMessage message = getInMessage(exchange);
        	String payload = sourceTransformer.toString(message.getContent());
        	if(payload.indexOf("started") != -1) {
        		logger.info("transaction successfull");
        	} else {
        		TransactionManager tm = (TransactionManager) context.getTransactionManager();
        		tm.setRollbackOnly();
        		logger.info("transaction rollbacked");
        	}
        } catch(Exception e) {
        	e.printStackTrace();
        }
        exchange.setStatus(ExchangeStatus.DONE);
        channel.send(exchange);
    }
}
